﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Script.Serialization;

using SF.Export;
using SF.Utilities;

namespace SF.WebClient.Controllers
{
    public class PublicController : Controller
    {
        public ViewResult ExampleIndex(string module, string extension)
        {
            ViewBag.Module = module;
            ViewBag.Extension = extension;

            return View();
        }

        public ViewResult QAIndex()
        {
            return View();
        }

        /// <summary>
        /// datagrid导出数据
        /// </summary>
        /// <param name="data">datagrid的data数据的json格式，将被反序列化成 DataTable </param>
        /// <param name="columns">datagrid的columns数据的json格式，将被反序列化成 DataTable[]，其中列是固定的“field、title、rowspan、colspan” </param>
        /// <param name="fileName">excel文件名</param>
        /// <param name="url">获取全部数据的地址，若该参数存在并获取到数据，则将忽略<see cref="data"/>参数的值</param>
        /// <param name="rowsField">得到全部数据（所有页）后从数据对象内获取的表示当前数据集的字段名</param>
        /// <param name="queryParams">发起“获取全部数据”的请求时传递的参数信息，将以 JSON 形式发送</param>
        /// <returns></returns>
        public FileResult ExportToExcelFromDatagrid([ModelBinder(typeof(DatagridRowsJsonBinder))]System.Data.DataTable data, [ModelBinder(typeof(DatagridColumnsJsonBinder))]System.Data.DataTable[] columns, string fileName, string url, string rowsField, string queryParams)
        {
            if (columns.Length == 0) { throw new Exception("列不存在，无法导出！"); }
            if (!string.IsNullOrWhiteSpace(url))
            {
                string hostUrl = "http://" + Request.Url.Host + ":" + Request.Url.Port;
                using (var hc = new HttpClient())
                {
                    string responseJson = string.Empty;
                    try
                    {
                        HttpContent httpContent = new StringContent(queryParams);
                        httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                        responseJson = hc.PostAsync(hostUrl + url, httpContent).Result.Content.ReadAsStringAsync().Result;
                    }
                    catch (Exception e) { throw new Exception("获取全部数据失败。", e); }

                    //返回的数据可能是{} 也可能是[]
                    if (responseJson.StartsWith("[") && responseJson.EndsWith("]"))
                    {
                        Newtonsoft.Json.Linq.JArray rows = Newtonsoft.Json.Linq.JArray.Parse(responseJson);
                        foreach (var item in rows)
                        {
                            var props = ((Newtonsoft.Json.Linq.JObject)item).Properties();
                            foreach (var p in props)
                            {
                                var value = p.Value;
                                if (value.Type == Newtonsoft.Json.Linq.JTokenType.Array) { p.Value = "[Array]"; }
                                else if (value.Type == Newtonsoft.Json.Linq.JTokenType.Object) { p.Value = "[Object]"; }
                            }
                        }
                        string json = SF.Utilities.Serialization.ToJson(rows);
                        data = SF.Utilities.Serialization.DeserializeJsToDataTable(json);
                    }
                    else if (responseJson.StartsWith("{") && responseJson.EndsWith("}"))
                    {
                        var result = SF.Utilities.Serialization.DeserializeJsToObject<Dictionary<string, object>>(responseJson);
                        if (!result.ContainsKey(rowsField))
                        { throw new Exception("获取全部数据后返回的数据中不存在[" + rowsField + "]属性，无法解析。"); }

                        var rows = result[rowsField];
                        if (!(rows is Newtonsoft.Json.Linq.JArray))
                        {
                            throw new Exception("获取全部数据后返回的数据中存在[" + rowsField + "]属性，但该属性里的数据不符合格式，无法解析。");
                        }
                        foreach (var item in (Newtonsoft.Json.Linq.JArray)rows)
                        {
                            var props = ((Newtonsoft.Json.Linq.JObject)item).Properties();
                            foreach (var p in props)
                            {
                                var value = p.Value;
                                if (value.Type == Newtonsoft.Json.Linq.JTokenType.Array) { p.Value = "[Array]"; }
                                else if (value.Type == Newtonsoft.Json.Linq.JTokenType.Object) { p.Value = "[Object]"; }
                            }
                        }
                        string json = SF.Utilities.Serialization.ToJson(rows);
                        data = SF.Utilities.Serialization.DeserializeJsToDataTable(json);
                    }
                    else
                    {
                        //无法识别
                        throw new Exception("获取全部数据后返回的信息格式无法识别。");
                    }
                }
            }

            IEnumerable<MergerCellParamModel> rules = null;
            DataTable dt = EasyuiDatagridExport.ParseColumnsAndRows(columns, data, out rules);

            var content = NPOIExport.ExportToExcel(dt, false, rules, true, true, false);

            if (string.IsNullOrWhiteSpace(fileName)) { fileName = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "导出"; }
            return File(content, "application/ms-excel", Url.Encode(fileName + ".xls"));
        }
    }
}